package jaux.tank.api.config;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import jaux.tank.admin.config.properties.TankProperties;
import jaux.tank.api.interceptor.SecurityInterceptor;

/**
 * 系统配置<br>
 *  配置拦截器
 *
 */
@Configuration
public class WebApiConfig implements WebMvcConfigurer {
	/**
	 * 定义排除拦截路径
	 */
	private   static final String[] EXCLUDE_PATH_PATTERN = {
			"/api/account/register"
			, "/api/account/login"
			, "/api/account/loginId"
			,"/api/**/login"
			,"/api/user/info"
	};
	public static final String EXCLUDE_PATH_PATTERN_STR= String.join(",", EXCLUDE_PATH_PATTERN);
	
	final SecurityInterceptor securityInterceptor;
	final TankProperties tankProperties;
	
	public WebApiConfig(SecurityInterceptor securityInterceptor, TankProperties tankProperties) {
		this.securityInterceptor = securityInterceptor;
		this.tankProperties = tankProperties;
	}

    /**
     * 注册自定义拦截器，添加拦截路径和排除拦截路径
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(securityInterceptor).addPathPatterns("/api/**").excludePathPatterns(getUrlAnonymous());

    }

    private List<String> getUrlAnonymous() {
		List<String> urlAnonymousLst = new ArrayList<>();
		urlAnonymousLst.addAll(Arrays.asList(EXCLUDE_PATH_PATTERN));
		urlAnonymousLst.addAll(Arrays.asList(tankProperties.getUrlAnonymous()));
		return urlAnonymousLst;
	}
    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
    	
    	converters.removeIf(c->c.getSupportedMediaTypes().contains(MediaType.APPLICATION_JSON));
		JoddHttpMessageConverter e = new JoddHttpMessageConverter();
		e.setSupportedMediaTypes(Arrays.asList(MediaType.APPLICATION_JSON
				, new MediaType("application", "*+json")));
		converters.add(e);
    }
}
